package com.pinyougou.manager.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.entity.PageResult;
import com.pinyougou.entity.Result;
import com.pinyougou.entity.SpecificationDTO;
import com.pinyougou.pojo.Specification;
import com.pinyougou.sellergoods.service.SpecificationService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("specification")
public class SpecificationController {
    @Reference
    private SpecificationService specificationService;

    @GetMapping("{id}")
    public SpecificationDTO detail(@PathVariable Integer id) {
        SpecificationDTO specificationDTO = specificationService.findById(id);
        return specificationDTO;
    }

    @GetMapping("list")
    public List<Specification> findAll() {
        List<Specification> specificationList = specificationService.findAll();
        return specificationList;
    }
    @GetMapping("list/options")
    public List<Map<Integer,String>> selectOptions(){
        List<Map<Integer,String>> options=specificationService.selectOptions();
        return options;
    }
    @GetMapping("list/{pageNum}/{pageSize}")
    public PageResult<Specification> findAll(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        PageResult<Specification> pageResult = specificationService.findByPage(pageNum, pageSize);
        return pageResult;
    }

    @PutMapping("search/{pageNum}/{pageSize}")
    public PageResult<Specification> search(@RequestBody(required = false) Specification specification,
                                            @PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        PageResult<Specification> pageResult = specificationService.findByPage(specification, pageNum, pageSize);
        return pageResult;
    }

    @PostMapping
    public Result add(@RequestBody SpecificationDTO specificationDTO) {
        try {
            specificationService.save(specificationDTO);
            return new Result(true, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加失败");
        }
    }

    @PutMapping
    public Result update(@RequestBody SpecificationDTO specificationDTO) {
        try {
            specificationService.update(specificationDTO);
            return new Result(true, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "更新失败");
        }
    }

    @DeleteMapping("delete")
    public Result delete(Integer[] ids) {
        if (ids == null || ids.length < 1)
            return new Result(false, "必须选中一个");
        try {
            specificationService.delete(ids);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }
}
